package com.sailing.lianxi.io.nio;

import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;

/**
 *监控文件变化
 * @author Administrator
 *
 */
public class WatchServiceTest {

	/**
	 * 监听文件系统变化
	 */
	public static void t1(){
		//获取文件系统的Watchservice对象
		try {
			WatchService watchService = FileSystems.getDefault().newWatchService();
			Paths.get("D:/test_data").register(watchService,
					StandardWatchEventKinds.ENTRY_CREATE,
					StandardWatchEventKinds.ENTRY_MODIFY,
					StandardWatchEventKinds.ENTRY_DELETE,
					StandardWatchEventKinds.OVERFLOW);
			
			while(true){
				//获取下一个文件变化事件
				WatchKey key = watchService.take();
				for (WatchEvent<?> event : key.pollEvents()) {
					System.out.println(event.context()+" 文件发生变化 "+event.kind()+"事件!");
				}
				//重设watchkey
				boolean valid = key.reset();
				//如果重设失败,则退出监听
				if(!valid){
					break;
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}
	
	public static void main(String[] args) {
		t1();
	}
}
